<template>
	<div id="studyVideo" ref="studyVideo"></div>
</template>

<script>
	import vapi from '@/api/index.js';
	import state from '@/config';
	import Player from 'xgplayer';
	export default {
		name: "xgvideo",
		data() {
			return {
				isLogin: !!state.isLogin(),
				freeTime: 360, // 试看秒数 6分钟
				offset: 1,
				pant: 120, // 心跳秒数
				player: null, //播放实例
				currentTime: 0, //当前时间
				lastCurrentTime: 0, //最后的时间
				maxLooktime: 0,
				nowlooktime: 0, //开始位置
				nowSecond: 0,
				showAlert: 0,
				isFullscreen: false,
				isBack: false,
				canPlay: false,
				timer: "", //定时器
				markRequestTime: "", //标记请求时间
			};
		},
		props: ['learnStatus', 'studentInfo', 'params'],
		mounted() {
			this.initPlayer(this.params);
		},
		onLoad: function({}) {

		},
		methods: {
			changeNode(params) {
				//console.log(params);
				//console.log('切换节:'+params.nodeId);
				console.log("已学进度:" + params.learnLength);
				if (params.autoplay) {
					uni.showLoading({
						title: '视频加载中...',
						mask: true
					});
				}
				this.initPlayer(params);
			},
			loop() {
				let _this = this;
				_this.timer = setTimeout(function() {
					//console.log('定时器执行');
					_this.sendheartbeat(_this.pant);
					_this.loop();
				}, (_this.pant) * 1000);

				// _this.timer = setInterval(function() {
				// 	//console.log('定时器执行');
				// 	_this.sendheartbeat(_this.pant);
				// 	//_this.loop();
				// }, (_this.pant + _this.offset) * 1000);

			},
			initData() {
				//重置数据
				if (this.player != null) {
					//切换的时候要销毁实例
					//this.player.destroy();
					this.$refs.studyVideo.innerHTML = "";
				}
				this.currentTime = this.lastCurrentTime = this.maxLooktime = this.nowlooktime = this.nowSecond = 0;
				this.canPlay = this.isFullscreen = this.isBack = false;
				//清空定时器
				if (this.timer) {
					clearInterval(this.timer);
				}
			},
			initPlayer(params) {
				let this_learnStatus = this.learnStatus;
				let __this = this;
				this.$nextTick(function() {
					let _this = this;
					_this.initData();
					var playerduration; //视频长度
					_this.currentTime = params.learnLength;
					_this.nowlooktime = params.learnLength;
					_this.maxLooktime = params.learnLength;
					_this.player = new Player({
						'id': 'studyVideo',
						'url': params.url,
						'poster': params.poster,
						'x5-video-player-type': 'h5', //微信同层播放
						'playsinline': false,
						"autoplay": params.autoplay | false,
						'fluid': true,
						'lang': 'zh-cn',
						'closeVideoClick': true,
						'closeVideoTouch': true,
						'lastPlayTime': params.learnLength,
						'lastPlayTimeHideDelay': 5, //提示文字展示时长（单位：秒）
						'keyShortcut': 'off',
						//使移动端支持双击暂停/播放
						'enableVideoDbltouch': true,
						//支持进度条只能拖动到已播过部分（播放器被接管或劫持时无效，比如iOS或安卓部分环境下）
						'allowSeekPlayed': _this.isLogin && params.classesId,

					});
					_this.player.on('play', function() {
						//console.log('播放...'+params.nodeId+"  _this.timer:"+_this.timer);
						//播放开始定时器
						clearInterval(_this.timer); //清空后重启定时器
						_this.loop();
						// _this.timer =setInterval(() => {
						// 	console.log('定时器执行');
						// 	_this.sendheartbeat(_this.pant);
						// },_this.pant*1000);
						//初始第一次
						_this.sendheartbeat(0);
					});
					_this.player.on('pause', function() {
						//console.log('暂停...'+params.nodeId);
						//暂停后停止并提交一次
						clearInterval(_this.timer);
						// console.log(new Date().getTime() / 1000 + "    " + _this.lastCurrentTime / 1000);
						let lastPart = (new Date().getTime() / 1000) - (_this.lastCurrentTime / 1000);
						// console.log(parseInt(lastPart),_this.isBack)
						if (parseInt(lastPart) > 1 && !_this.isBack) {
							_this.sendheartbeat(lastPart);
						}
					});
					_this.player.on('ended', function() {
						console.log('播放完成...');
						//暂停后停止并提交一次
						clearInterval(_this.timer);
						let lastPart = new Date().getTime() / 1000 - _this.lastCurrentTime / 1000;
						if (parseInt(lastPart) > 1) {
							_this.sendheartbeat(lastPart + 2);
						} else if (parseInt(lastPart) == 0) {
							_this.sendheartbeat(lastPart + 10);
						}
						// 自动跳下一节
						// _this.changeNextNode();
					});

					_this.player.on('waiting', function() {
						console.log('waiting...');
						uni.showLoading({
							title: '视频加载中...',
							mask: true
						});
						_this.canPlay = false;

					});
					_this.player.on('canplay', function() {
						if (!_this.canPlay) {
							uni.hideLoading(); //视频可播放
						}
						// console.log('canplay...');
					});
					// 监听进入全屏状态
					_this.player.on('requestFullscreen', function() {
						_this.isFullscreen = true;
					});
					// 监听退出全屏状态
					_this.player.on('exitFullscreen', function() {
						_this.isFullscreen = false;
					});
					_this.player.on('timeupdate', function() {
						playerduration = _this.player.duration;
						_this.currentTime = _this.player.currentTime;
						var timeDisplay = Math.floor(_this.currentTime); //观看位置
						var partTime = timeDisplay - _this.nowlooktime; //观看片段

						if (_this.nowSecond != timeDisplay) {
							// if (uni.getSystemInfoSync().platform == 'ios' && timeDisplay>0) { //在苹果系统下
							// 	// 往后拖动处理
							// 	var nowPlayTime = new Date();
							// 	nowPlayTime = nowPlayTime.getTime();
							// 	var markRequestTimeJian = Math.ceil((nowPlayTime - __this.markRequestTime) / 1000);
							// 	console.log(partTime,markRequestTimeJian,params.learnLength,this_learnStatus)
							// 	if (partTime > markRequestTimeJian && params.learnLength !=-1 && this_learnStatus != 2) {
							// 		_this.player.pause();
							// 		alert("禁止拖动");
							// 		_this.player.currentTime = _this.nowlooktime;
							// 		partTime = timeDisplay - _this.nowlooktime;
							// 		return false;
							// 	}
							// }


							_this.nowSecond = timeDisplay;
							//console.log("播放位置:"+_this.nowSecond+" 间隔:"+partTime);
							if (timeDisplay >= _this.freeTime && !_this.player.paused) {
								_this.freePlayOver();
							}
						}
						if (timeDisplay > _this.maxLooktime) {
							_this.maxLooktime = timeDisplay;
							_this.isBack = false;
						} else {
							_this.isBack = true;
						}

						if (this_learnStatus != null && this_learnStatus != 2 &&
							partTime == _this.pant) {
							_this.nowlooktime = timeDisplay;
						}

					});
				});
			},
			freePlayOver() {
				//未登录 未购买
				if (!this.isLogin || !this.params.classesId) {
					if (this.isFullscreen) {
						this.player.exitFullscreen(this.player.root);
						this.player.exitCssFullscreen();
					}
					this.player.currentTime = this.freeTime;
					this.player.pause();
					if (new Date().getTime() - this.showAlert > 250) {
						alert("试看已结束");
						this.showAlert = new Date().getTime();
					}
					// if(uni.getSystemInfoSync().platform == 'ios'){
					// 	if(new Date().getTime() -this.showAlert>250){
					// 		alert("试看已结束");
					// 		this.showAlert = new Date().getTime();
					// 	}
					// }else{
					// 	this.$uni.msg('试看已结束');
					// }

					for (let i = 1; i < 100; i++) {
						clearInterval(i);
					}
					var that = this;
					var courseStatus = this.params.courseStatus;

					var msg = "试看结束，如需继续观看，请购买课程，是否加入购物车？";
					if (courseStatus == 0) {
						msg = "试看结束，如需继续观看，请购买课程，课程已在购物车中，是否进入购物车去结算？";
					} else if (courseStatus == 2) {
						msg = "试看结束，如需继续观看，请购买课程，课程有存在支付中订单，是否继续支付？";
					} else {
						uni.showModal({
							title: '提示',
							content: msg,
							success: function(res) {
								if (res.confirm) {
									//调用父页面播放器页面的加入购物车方法
									that.$emit("handleShoppingCart");
								} else if (res.cancel) {
									//console.log('用户点击取消');
								}
							}
						});
					}
				}
			},
			sendheartbeat(len) {
				var nowTime = new Date();
				this.markRequestTime = nowTime.getTime();
				this.lastCurrentTime = new Date().getTime();
				len = Math.floor(len);
				//console.log("maxLooktime "+this.maxLooktime+"   nowSecond"+this.nowSecond);
				let backed = this.maxLooktime > 0 && this.nowSecond > 0 && this.nowSecond < this.maxLooktime;
				//没有登录，没有购买
				if (!this.isLogin || !this.params.classesId || backed) {
					//console.log('取消心跳  长度:'+len);
					return;
				}
				console.log('心跳===  长度:' + len + "  learnStatus:" + this.learnStatus + "  chapterId：" + this.params
					.chapterId);

				let tmpToken = this.learningToken; //暂存上一次的token
				this.learningToken = len == 0 ? "" : this.learningToken;
				this.$api.heartbeat({
					chapterId: this.params.chapterId,
					classesId: this.params.classesId,
					courseId: this.params.courseId,
					learningToken: this.learningToken,
					nodeId: this.params.nodeId,
					sourceType: 2,
					studentId: state.storage(['user_info', 'id']),
					viewingLength: len
				}, e => {
					//this.lastCurrentTime = new Date().getTime();
					if (e.status == '0') {
						this.learningToken = e.data;
					} else if (e.status == '1') {
						this.player.pause(); //暂停
						uni.showModal({
							title: '提示',
							content: e.data,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									window.location.reload();
								} else if (res.cancel) {}
							}
						});
					} else if (e.status == '9999') {
						this.learningToken = tmpToken;
						uni.showToast({
							title: e.data,
							duration: 2000,
							icon: 'error'
						});
					} else {
						this.learningToken = "";
					}
					this.queryNewestStudent(); //更新前端进度
				});
			},
			// 请求更新当前节
			queryNewestStudent: function() {
				this.$emit("queryNewestStudent", this.params, this.params);
			},
			// 请求播放下一节
			changeNextNode: function() {
				console.log("播放切换节函数" + this.params.chapterId, this.params.nodeId);
				this.$emit("changeNextNode", this.params.chapterId, this.params.nodeId);
			}
		}
	}
</script>

<style>

</style>
